//
//  MonitorCenterViewController.swift
//  TJJPT
//
//  Created by FENGYL on 2017/7/15.
//  Copyright © 2017年 FENGYL. All rights reserved.
//

import UIKit
import SVProgressHUD

class MonitorCenterViewController: UIViewController,BMKMapViewDelegate {
    
    var baiduMapView:BMKMapView?
    var aMapView:MAMapView?
    
    var isFullScreen = false
    var isSatellite = false
    
    var index = 0
    
    let monitorCenterViewControllerForAMap = MonitorCenterViewControllerForAMap()
    
    @IBOutlet weak var mapView: UIView!
    
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    

    override func viewDidLoad() {
        super.viewDidLoad()

        setUpView()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        
        baiduMapView?.delegate = self
        
        aMapView?.delegate = monitorCenterViewControllerForAMap

    }
    
    override func viewWillDisappear(_ animated: Bool) {
        
        baiduMapView?.delegate = nil
        
        aMapView?.delegate = nil
        
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    // MARK: - 初始化
    func setUpView() {
        
//        // MARK: 设置view
//        self.view.height = STATIC_VALUE_SCREEN_HEIGHT - 20 - (self.navigationController?.navigationBar.height)!
//        
//        self.view.y = 20 + (self.navigationController?.navigationBar.height)!
        
        // MARK: 标题
        self.title = NSLocalizedString(LOCALIZABLE_STRING_REAL_TIME_TRACK, comment: "")
        
        // MARK: 用哪个地图
        if UserModel.userModel.selectedMap == LOCALIZABLE_STRING_BAIDU_MAP {
            
            baiduMapView = BMKMapView.init(frame: self.view.bounds)
            
            baiduMapView?.showMapScaleBar = true
            
            self.mapView.addSubview(baiduMapView!)
            
        }else if UserModel.userModel.selectedMap == LOCALIZABLE_STRING_AMAP{
            
            ///地图需要v4.5.0及以上版本才必须要打开此选项（v4.5.0以下版本，需要手动配置info.plist）
            AMapServices.shared().enableHTTPS = true
            
            ///初始化地图
            aMapView = MAMapView.init(frame: self.view.bounds)
            
            aMapView?.showsScale = true
            
            ///把地图添加至view
            self.mapView.addSubview(aMapView!)
            
        }
        
        // MARK: 获取基本信息
        SVProgressHUD.show()
        
        NetworkCommand.getLastStatusData(listSerialNumber: nil, id: nil, clientType: nil, tokenPass: nil, success: { (response) in
            
            self.addAnnotation()
            
            SVProgressHUD.dismiss()
            
        }) { (Error) in
            
            SVProgressHUD.showError(withStatus: NSLocalizedString(LOCALIZABLE_STRING_FAILURE, comment: ""))
            
            SVProgressHUD.dismiss(withDelay: 1)
            
        }
        
        
        // MARK: 设置顶上三个按钮
        setUpTopButton()
        
        
        
        
    }
    
    // MARK: - 设置顶上三个按钮
    func setUpTopButton() {
        
        // MARK: 全屏按钮
        let fullScreenButton = UIButton.init(frame: CGRect.init(x: STATIC_VALUE_SCREEN_WIDTH - 20 - 27, y: 20, width: 27, height: 23))
        
        fullScreenButton.setImage(#imageLiteral(resourceName: "tjj_icon_fulScreen"), for: .normal)
        
        fullScreenButton.addTarget(self, action: #selector(setUpFullScreen), for: .touchUpInside)
        
        
        // MARK: 卫星地图按钮
        let satelliteMapButton = UIButton.init(frame: CGRect.init(x: fullScreenButton.frame.minX - 20 - 27, y: 20, width: 27, height: 23))
        
        satelliteMapButton.setImage(#imageLiteral(resourceName: "tjj_icon_Satellite"), for: .normal)
        
        satelliteMapButton.addTarget(self, action: #selector(setUpSatelliteMap), for: .touchUpInside)
        
        
        if UserModel.userModel.selectedMap == LOCALIZABLE_STRING_BAIDU_MAP {
            
            self.baiduMapView?.addSubview(fullScreenButton)
            
            self.baiduMapView?.addSubview(satelliteMapButton)
            
        }else if UserModel.userModel.selectedMap == LOCALIZABLE_STRING_AMAP {
            
            self.aMapView?.addSubview(fullScreenButton)
            
            self.aMapView?.addSubview(satelliteMapButton)
            
        }
        
    }
    
    // MARK: - 全屏
    func setUpFullScreen() {
        
//        if isFullScreen {
//            
//            self.navigationController?.setNavigationBarHidden(false, animated: true)
//            
//        }else {
//            
//            self.navigationController?.setNavigationBarHidden(true, animated: true)
//            
//        }
//        
//        isFullScreen = !isFullScreen
        
        let window = UIApplication.shared.keyWindow
        
        if UserModel.userModel.selectedMap == LOCALIZABLE_STRING_BAIDU_MAP {
            
            self.baiduMapView?.removeFromSuperview()
            
            if isFullScreen {
                
                self.baiduMapView?.frame = self.mapView.bounds
                
                self.mapView.addSubview(self.baiduMapView!)
                
            }else {
                
                self.baiduMapView?.frame = (window?.bounds)!
                
                window?.addSubview(self.baiduMapView!)
                
            }
            
        }else if UserModel.userModel.selectedMap == LOCALIZABLE_STRING_AMAP {
            
            self.aMapView?.removeFromSuperview()
            
            if isFullScreen {
                
                self.aMapView?.frame = self.mapView.bounds
                
                self.mapView.addSubview(self.aMapView!)
                
            }else {
                
                self.aMapView?.frame = (window?.bounds)!
                
                window?.addSubview(self.aMapView!)
                
                
            }
            
            
        }
        
        isFullScreen = !isFullScreen
        
    }
    
    // MAKR: - 卫星地图
    func setUpSatelliteMap() {
        
        if UserModel.userModel.selectedMap == LOCALIZABLE_STRING_BAIDU_MAP {
            
            if isSatellite {
                
                self.baiduMapView?.mapType = UInt(BMKMapTypeStandard)
                
            }else {
                
                self.baiduMapView?.mapType = UInt(BMKMapTypeSatellite)
                
                
            }
            
        }else if UserModel.userModel.selectedMap == LOCALIZABLE_STRING_AMAP {
            
            if isSatellite {
                
                self.aMapView?.mapType = .standard
                
            }else {
                
                self.aMapView?.mapType = .satellite
                
                
            }
            
        }
        
        isSatellite = !isSatellite
        
    }
    
    // MARK: - 转换百度坐标
    func coorForWGS84ToBd09(coor:CLLocationCoordinate2D) -> CLLocationCoordinate2D {
        
        //转换WGS84坐标至百度坐标(加密后的坐标)
        let testdic = BMKConvertBaiduCoorFrom(coor, BMK_COORDTYPE_GPS)
        
//        print(testdic!)
        
        //解密加密后的坐标字典
        let baiduCoor = BMKCoorDictionaryDecode(testdic)//转换后的百度坐标
        
        return baiduCoor
        
    }
    
    // MARK: - 添加大头针
    func addAnnotation() {
        
        if UserModel.userModel.lastStatusDataArray != nil {
            
            if (UserModel.userModel.lastStatusDataArray?.count)! > 0 {
                
                index = 0
                
                for dict in UserModel.userModel.lastStatusDataArray! {
                    
                    let lastStatusData = LastStatusData.mj_object(withKeyValues: dict)
                    
                    if lastStatusData?.Lat != nil && lastStatusData?.Lng != nil {
                        
                        let coor = CLLocationCoordinate2D.init(latitude: (lastStatusData?.Lat?.doubleValue)!, longitude: (lastStatusData?.Lng?.doubleValue)!)
                        
                        if UserModel.userModel.selectedMap == LOCALIZABLE_STRING_BAIDU_MAP {
                            
                            let coordinate = coorForWGS84ToBd09(coor: coor)
                            
                            let annotation = BMKPointAnnotation.init()
                            annotation.coordinate = coordinate
                            annotation.title = ""
                            self.baiduMapView?.addAnnotation(annotation)
                            
                            self.baiduMapView?.setCenter(coordinate, animated: true)
                            
                            
                        }else if UserModel.userModel.selectedMap == LOCALIZABLE_STRING_AMAP {

                            let coordinate = AMapCoordinateConvert(coor, .GPS)
                            
                            let annotation = MAPointAnnotation()
                            annotation.coordinate = coordinate
                            annotation.title = lastStatusData?.SerialNumber
                            self.aMapView?.addAnnotation(annotation)
                            
                            self.aMapView?.setCenter(coordinate, animated: true)
                            
                            
                        }
                        
                        
                    }
                    
                    index += 1
                    
                }
                
            }
            
        }
        
    }
    
    
    // MARK: - 初始化LHPlayViewControllerForAMap
//    func setUpLHPlayViewControllerForAMap() {
//        
//        if UserModel.userModel.lastStatusDataArray != nil {
//            
//            if (UserModel.userModel.lastStatusDataArray?.count)! > 0 {
//                
//                let dict = UserModel.userModel.lastStatusDataArray?[index]
//                
//                let h = LastStatusData.mj_object(withKeyValues: dict)
//                
//                if h != nil {
//                    
//                    //serialNumber
//                    let ser = NSLocalizedString(LOCALIZABLE_STRING_DEVICE_SERIAL_NUMBER, comment: "") + ":" + (h?.SerialNumber)!
//                    
//                    //time
//                    let dateFormatter = DateFormatter.init()
//                    dateFormatter.dateFormat = STATIC_VALUE_DATE_FORMATTER + " " + STATIC_VALUE_TIME_FORMATTER
//                    
//                    let date = Date.init(timeIntervalSince1970: (h?.ConnTime?.doubleValue)!)
//                    
//                    let timeString = dateFormatter.string(from: date)
//                    
//                    let time = NSLocalizedString(LOCALIZABLE_STRING_LAST_CONNECTED, comment: "") + ":" + timeString
//                    
//                    //displayName
//                    var displayName = NSLocalizedString(LOCALIZABLE_STRING_DISPLAY_NAME, comment: "") + ":"
//                    if UserModel.userModel.devicesByAccountArray != nil {
//                        
//                        if (UserModel.userModel.devicesByAccountArray?.count)! > 0 {
//                            
//                            for dict in UserModel.userModel.devicesByAccountArray! {
//                                
//                                let devicesByAccount = DevicesByAccount.mj_object(withKeyValues: dict)
//                                
//                                displayName = NSLocalizedString(LOCALIZABLE_STRING_DISPLAY_NAME, comment: "") + ":" + (devicesByAccount?.DisplayName)!
//                                
//                            }
//                            
//                        }
//                        
//                    }
//                    
//                    
//                    
//                    monitorCenterViewControllerForAMap.serialNumber = ser
//                    monitorCenterViewControllerForAMap.time = time
//                    monitorCenterViewControllerForAMap.displayName = displayName
//                }
//                
//            }
//            
//        }
//        
//        
//        
//        
//    }
    
    // MARK: - 设置百度annotationView
    func setUpBMKAnnotationView(annotationView:MonitorBMKCustomAnnotationView) {
        
            if (UserModel.userModel.lastStatusDataArray?.count)! > 0 {
                
                let dict = UserModel.userModel.lastStatusDataArray?[index]
                
                let h = LastStatusData.mj_object(withKeyValues: dict)
                
                if h != nil {
                    
                    //serialNumber
                    let ser = NSLocalizedString(LOCALIZABLE_STRING_DEVICE_SERIAL_NUMBER, comment: "") + ":" + (h?.SerialNumber)!
                    
                    //time
                    let dateFormatter = DateFormatter.init()
                    dateFormatter.dateFormat = STATIC_VALUE_DATE_FORMATTER + " " + STATIC_VALUE_TIME_FORMATTER
                    
                    let date = Date.init(timeIntervalSince1970: (h?.ConnTime?.doubleValue)!)
                    
                    let timeString = dateFormatter.string(from: date)
                    
                    let time = NSLocalizedString(LOCALIZABLE_STRING_LAST_CONNECTED, comment: "") + ":" + timeString
                    
                    //displayName
                    var displayName = NSLocalizedString(LOCALIZABLE_STRING_DISPLAY_NAME, comment: "") + ":"
                    if UserModel.userModel.devicesByAccountArray != nil {
                        
                        if (UserModel.userModel.devicesByAccountArray?.count)! > 0 {
                            
                            for dict in UserModel.userModel.devicesByAccountArray! {
                                
                                let devicesByAccount = DevicesByAccount.mj_object(withKeyValues: dict)
                                
                                if devicesByAccount?.SerialNumber == h?.SerialNumber {
                                    
                                    displayName = NSLocalizedString(LOCALIZABLE_STRING_DISPLAY_NAME, comment: "") + ":" + (devicesByAccount?.DisplayName)!
                                    
                                }
                                
                            }
                            
                        }
                        
                    }
                    
                    annotationView.serialNumber = ser
                    annotationView.time = time
                    annotationView.displayName = displayName
                    
                }
                
            }
        
        
        
        
    }
    
    
    // MARK: - 返回AnnotationView  delegate
    func mapView(_ mapView: BMKMapView!, viewFor annotation: BMKAnnotation!) -> BMKAnnotationView! {
        
        if annotation.isKind(of: BMKPointAnnotation.classForCoder()) {
            
            let newAnnotaitonView = MonitorBMKCustomAnnotationView.init(annotation: annotation, reuseIdentifier: "myAnnotation")
            
            setUpBMKAnnotationView(annotationView: newAnnotaitonView!)
            
            newAnnotaitonView?.image = #imageLiteral(resourceName: "z_gps_realTime_GPS")
            
            newAnnotaitonView?.centerOffset = CGPoint.init(x: 0, y: -((newAnnotaitonView?.frame.size.height)! / 2))
            
//            newAnnotaitonView?.setSelected(true, animated: true)
            
            return newAnnotaitonView
            
        }
        
        return nil
        
    }
    
    func mapView(_ mapView: BMKMapView!, didSelect view: BMKAnnotationView!) {
        
        view.setSelected(true, animated: true)
        
        view.paopaoView.isHidden = true
        
    }
    
    func mapView(_ mapView: BMKMapView!, didDeselect view: BMKAnnotationView!) {
        
        view.setSelected(false, animated: true)
        
    }
    
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}


class MonitorCenterViewControllerForAMap: NSObject,MAMapViewDelegate {
    
    var serialNumber:String?
    var time:String?
    var displayName:String?
    
    // MARK: - 初始化MonitorCenterViewControllerForAMap
    func setUpMonitorCenterViewControllerForAMap(annotationView:MonitorCustomAnnotationView,serialNumber:String) {
        
        if UserModel.userModel.lastStatusDataArray != nil {
            
            if (UserModel.userModel.lastStatusDataArray?.count)! > 0 {
                
                for dict in UserModel.userModel.lastStatusDataArray! {
                    
                    let h = LastStatusData.mj_object(withKeyValues: dict)
                    
                    if h != nil {
                        
                        if h?.SerialNumber == serialNumber {
                            
                            //serialNumber
                            let ser = NSLocalizedString(LOCALIZABLE_STRING_DEVICE_SERIAL_NUMBER, comment: "") + ":" + (h?.SerialNumber)!
                            
                            //time
                            let dateFormatter = DateFormatter.init()
                            dateFormatter.dateFormat = STATIC_VALUE_DATE_FORMATTER + " " + STATIC_VALUE_TIME_FORMATTER
                            
                            let date = Date.init(timeIntervalSince1970: (h?.ConnTime?.doubleValue)!)
                            
                            let timeString = dateFormatter.string(from: date)
                            
                            let time = NSLocalizedString(LOCALIZABLE_STRING_LAST_CONNECTED, comment: "") + ":" + timeString
                            
                            //displayName
                            var displayName = NSLocalizedString(LOCALIZABLE_STRING_DISPLAY_NAME, comment: "") + ":"
                            if UserModel.userModel.devicesByAccountArray != nil {
                                
                                if (UserModel.userModel.devicesByAccountArray?.count)! > 0 {
                                    
                                    for dict in UserModel.userModel.devicesByAccountArray! {
                                        
                                        let devicesByAccount = DevicesByAccount.mj_object(withKeyValues: dict)
                                        
                                        if devicesByAccount?.SerialNumber == serialNumber {
                                            
                                            displayName = NSLocalizedString(LOCALIZABLE_STRING_DISPLAY_NAME, comment: "") + ":" + (devicesByAccount?.DisplayName)!
                                            
                                        }

                                        
                                    }
                                    
                                }
                                
                            }
                            
                            
                            
                            annotationView.serialNumber = ser
                            annotationView.time = time
                            annotationView.displayName = displayName
                            
                        }
                        
                    }
                    
                }
                
            }
            
        }
        
        
        
        
    }
    
    // MARK: - annotationView代理
    func mapView(_ mapView: MAMapView!, viewFor annotation: MAAnnotation!) -> MAAnnotationView! {
        
        if annotation.isKind(of: MAPointAnnotation.classForCoder()) {

            let newAnnotaitonView = MonitorCustomAnnotationView.init(annotation: annotation, reuseIdentifier: "myAnnotation")

            setUpMonitorCenterViewControllerForAMap(annotationView: newAnnotaitonView!, serialNumber: annotation.title!)
            
            
            
            
            newAnnotaitonView?.image = #imageLiteral(resourceName: "z_gps_realTime_GPS")
            
            newAnnotaitonView?.centerOffset = CGPoint.init(x: 0, y: -((newAnnotaitonView?.frame.size.height)! / 2))
            
            newAnnotaitonView?.canShowCallout = true

            
            
            
            return newAnnotaitonView
            
        }
        
        return nil
        
    }

    func mapView(_ mapView: MAMapView!, didSelect view: MAAnnotationView!) {
        
        view.setSelected(true, animated: true)
        
    }
    
    func mapView(_ mapView: MAMapView!, didDeselect view: MAAnnotationView!) {
        
        view.setSelected(false, animated: true)
        
    }
    
}
